package com.itheima.web.controller;

import com.itheima.domain.system.Module;
import com.itheima.domain.system.User;
import com.itheima.service.system.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;


@Controller
public class
LoginController extends BaseController {

    @Autowired
    private UserService userService;
    /*@Autowired
    private ModuleService moduleService;
    @Autowired
    private RoleService roleService;*/

    /*//登录用户判断
    @RequestMapping("/login")
    public String loin(String email, String password) {
        //判断用户输入的数据是否有效
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password)) {
            return "forward:/login.jsp";
        }
        //通过邮箱查找用户信息
        User user = userService.findByEmail(email);
        if (user != null && user.getPassword().equals(password)) {
            //邮箱和密码正确，保存登陆信息后跳转
            session.setAttribute("loginUser", user);
            //查询用户所拥有的操作权限
            List<Module> modules = userService.findModuleByUserId(user.getId());
            session.setAttribute("modules", modules);
            return "home/main";
        } else {
            //登陆失败，保存错误信息然后返回登陆页
            request.setAttribute("error", "输入的邮箱或者密码错误");
            return "forward:/login.jsp";
        }
    }*/

    /**
     * 通过shiro进行登录认证
     */
    @RequestMapping("/login")
    public String login(String email, String password) {
        try {
            //获取subject
            Subject subject = SecurityUtils.getSubject();
            //构造用户名和密码
            UsernamePasswordToken upToken = new UsernamePasswordToken(email, password);
            //借助subject完成登陆
            subject.login(upToken);
            //通过shiro获取用户对象，保存到session中
            User user = (User) subject.getPrincipal();//获取安全的对象数据
            session.setAttribute("loginUser", user);
            //获取菜单数据    `
            List<Module> moduleList = userService.findModuleByUserId(user.getId());
            session.setAttribute("modules", moduleList);
            return "home/main";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error","邮箱或密码错误!");
            return "forward:/login.jsp";
        }
    }

    //用于进入主页后内容区域显示首页信息
    @RequestMapping("/home")
    public String home() {
        return "home/home";
    }

    //退出登录
    @RequestMapping("/logout")
    public String loginOut() {
        // shiro也提供了退出方法(清除shiro的认证信?息)
//        SecurityUtils.getSubject().logout();
        // 先清空session中登陆用户
        session.removeAttribute("loginUser");
        // 销毁服务端session
        session.invalidate();
        return "forward:/login.jsp";
    }


}
